package com.ddstation.click.task;

import com.alibaba.fastjson.JSONObject;
import com.ddstation.click.entity.ClickInstitutionInfoEntity;
import com.ddstation.click.entity.EnforcementInfoEntity;
import com.ddstation.common.district.entity.MaDistrictEntity;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.crud.entity.DtInvsManageInstitutionEntity;
import com.ddstation.crud.mapper.DtInvsManageInstitutionMapper;
import com.ddstation.hzsc_invs.autonomy_examination.mapper.DtInvsEnforcementDataMapper;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.master.mapper.MaDataDictionaryMapper;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@MapperScan({"com.ddstation.master.mapper","com.ddstation.crm.institution.mapper","com.ddstation.crud.mapper"})
public class ClickDataTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClickDataTask.class);

    private static final String COMMON_URL = "http://scqwebs.bjclick.cn";

    @Resource
    private MaDataDictionaryMapper maDataDictionaryMapper;
    @Resource
    private DtInvsManageInstitutionMapper dtInvsManageInstitutionMapper;
    @Resource
    private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
    @Resource
    private DtInvsEnforcementDataMapper dtInvsEnforcementDataMapper;

    //上城区域ID
    private static final String INVS_INSTITUTION_ID = "00000007";

    /**
     * 定时任务入口
     */
    @Scheduled(fixedRate = 432000000)
//    @Scheduled(fixedRate = 60000)
    public void task() {
        LOGGER.info("========== ClickDataTask Start ==========");
//        getEnforcementInfo();
        //需要业务机构字段长度改变，暂关闭使用
        if (true) {
            return;
        }

        try {

            DtInvsManageInstitutionEntity dtInvsManageInstitutionEntity = dtInvsManageInstitutionMapper.selectByPrimaryKey(INVS_INSTITUTION_ID);
            if(dtInvsManageInstitutionEntity == null) {
                return;
            }

            Integer province = Integer.valueOf(dtInvsManageInstitutionEntity.getProvince());
            Integer city = Integer.valueOf(dtInvsManageInstitutionEntity.getCity());
            Integer county = Integer.valueOf(dtInvsManageInstitutionEntity.getCounty());

            //拉取医疗机构信息
            getInstituionInfo(province, city, county);

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        LOGGER.info("========== ClickDataTask End ==========");
    }

    public void getEnforcementInfo()  {
        LOGGER.info("开始获取执法结果" );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDate = sdf.format( DateUtil.addDay(new Date(),-2));
        String secondDate = sdf.format( DateUtil.addDay(new Date(),-1));
        firstDate = "2018-01-01";
        secondDate = "2020-11-27";
        String result = doPost(COMMON_URL + "/Upload.asmx/getYljgCfxx", "ruCan=|"+firstDate+"|" + secondDate);
        LOGGER.info("result =>{}" , result);
        if(StringUtils.isNotEmpty(result)){
            int beginIndex = result.indexOf(">[");
            int endIndex = result.indexOf("]<");
            if (beginIndex != -1 &&  endIndex != -1 && result.length() >= (endIndex+1)) {
                result = result.substring(beginIndex+1, endIndex+1);
                List<EnforcementInfoEntity> tempList = JSONObject.parseArray(result, EnforcementInfoEntity.class);
                if(tempList.size()>0){
                    dtInvsEnforcementDataMapper.batchInsert(tempList);
                }
            }
        }
    }

    public void getInstituionInfo(Integer province, Integer city, Integer county) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(new Date());

        String result = doPost(COMMON_URL + "/Upload.asmx/getYljg", "ruCan=||2018-1-1|" + currentDate);
        //String result = doPost(COMMON_URL + "/Upload.asmx/getYljg", "ruCan=||2020-5-1|2020-9-3");
        //String result = doPost(COMMON_URL + "/Upload.asmx/getYljg", "ruCan=上城区|||");

        LOGGER.info("result =>" + result);
        if(!StringUtils.isEmpty(result)) {
            int beginIndex = result.indexOf("[");
            int endIndex = result.indexOf("]");
            if (beginIndex != -1 &&  endIndex != -1 && result.length() >= (endIndex+1)) {
                result = result.substring(beginIndex, endIndex+1);
                List<ClickInstitutionInfoEntity> tempList = JSONObject.parseArray(result, ClickInstitutionInfoEntity.class);

                //街道
                List<MaDistrictEntity> townList = dtHealthManageInstitutionMapper.selectDisctrictInfo(null, county);
                if (townList.size() == 0) {
                    return;
                }

                //科室
                List<MaDataDictionaryEntity> technicalOfficesList = maDataDictionaryMapper.selectByCategoryId("technical_offices");
                if (technicalOfficesList.size() == 0) {
                    return;
                }

                List<DtHealthManageInstitutionEntity> institutionList = new ArrayList<>();
                for(ClickInstitutionInfoEntity temp:tempList) {
                    String town = getTownByName(townList, temp.getXiangjiedao());
                    if (!StringUtils.isEmpty(town)) {
                        DtHealthManageInstitutionEntity entity = new DtHealthManageInstitutionEntity();
                        entity.setUnderInvs(1);
                        entity.setPrescriptionInvs(1);
                        entity.setId(temp.getMid());
                        entity.setName(temp.getDwmc());
                        entity.setShortName(temp.getMc());
                        entity.setBusinessLicenceCd(temp.getXkzh());
                        entity.setAddress(temp.getDwdz());
                        entity.setProvince(province);
                        entity.setCity(city);
                        entity.setCounty(county);
                        //entity.setCounty(temp.getXianqu());
                        entity.setTown(town);
                        entity.setOwnerName(temp.getJingyingzhexm());
                        entity.setTel(temp.getSj1());
                        entity.setTechnicalOffices(transferTechnicalOffices(technicalOfficesList, temp.getXkxm()));
                        String[] dateArray = temp.getXkzyxq().split("至");
                        if(dateArray.length == 2) {
                            entity.setOccupationalLicenceStartDate(transferStringToDate(dateArray[0].replace(" ", "")));
                            entity.setOccupationalLicenceEndDate(transferStringToDate(dateArray[1].replace(" ", "")));
                        }
                        institutionList.add(entity);
                    }
                }
                dtHealthManageInstitutionMapper.clickInstitutionInsertOrUpdate(institutionList);
            }
        }
    }

    public String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            LOGGER.debug(String.valueOf(connection.getResponseCode()));
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 10*1024*1024);

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }

                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    /**
     * 街道名称 转 id
     * @param towns 街道列表
     * @param name 街道名称
     * @return
     */
    public String getTownByName(List<MaDistrictEntity> towns, String name) {

        String town = null;
        for (MaDistrictEntity entity:towns) {
            if (entity.getName().equals(name)) {
                town = String.valueOf(entity.getId());
            }
        }

        return town;
    }

    /**
     * String 转 Date
     * @param "2020-08-26"、"2020/08/26"
     * @return
     */
    public Date transferStringToDate(String dateString) {

        Date date = null;
        try {
            SimpleDateFormat simpleDateFormat;
            if (dateString.indexOf("-") != -1) {
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            } else {
                simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            }
            date = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    /**
     * 科目名称 转 id
     * @param list
     * @param technicalOffices
     * @return
     */
    public String transferTechnicalOffices(List<MaDataDictionaryEntity> list, String technicalOffices) {
        String result = "";
        try {
            if(!StringUtils.isEmpty(technicalOffices)) {
                technicalOffices = technicalOffices.replaceAll("\\s|\\*", "");
                technicalOffices = technicalOffices.replaceAll(",|;|、|；|，|、", "/");
                String[] tempArr = technicalOffices.split("/");
                List resultList = new ArrayList();;
                for (int i=0; i < tempArr.length; i++) {
                    for(MaDataDictionaryEntity entity:list) {
                        if(entity.getFullName().indexOf(tempArr[i]) != -1) {
                            if (!resultList.contains(entity.getValue())) {
                                resultList.add(entity.getValue());
                            }
                            break;
                        }
                    }
                }

                for (int j=0; j < resultList.size(); j++) {
                   if(j == resultList.size() - 1) {
                       result += resultList.get(j);
                   } else {
                       result += resultList.get(j) + ",";
                   }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


}
